package com.snails.net.restful.common;

import com.snails.net.SnailsNet;
import com.snails.net.restful.RestService;
import com.snails.net.restful.rx.RxRestService;
import com.snails.net.retrofit.RetrofitClient;
import com.snails.net.retrofit.cookie.CookieManger;

/**
 * @author  lawrence
 * @date    2019-04-11
 */
public final class RestCreator {

    private RestCreator() { }

    private static final class RetrofitHolder {
        private static final RetrofitClient CLIENT = new RetrofitClient.Builder()
                .baseUrl(SnailsNet.instance().configuration().restful().baseUrl())
                .timeOut(SnailsNet.instance().configuration().restful().default_time_out)
                .rTimeOut(SnailsNet.instance().configuration().restful().default_r_time_out)
                .wTimeOut(SnailsNet.instance().configuration().restful().default_w_time_out)
                .cache(SnailsNet.instance().configuration().restful().cache_file,
                        SnailsNet.instance().configuration().restful().cache_size)
                .debug(SnailsNet.instance().configuration().restful().debug,
                        SnailsNet.instance().configuration().restful().loggerTag)
                .moreBaseUrl(SnailsNet.instance().configuration().restful().more_base_url)
                .addInterceptors(SnailsNet.instance().configuration().restful().interceptors())
                .addNetworkInterceptors(SnailsNet.instance().configuration().restful().networkInterceptors())
                .build(SnailsNet.instance().getCtx());
    }

    private static final class RxRestServiceHolder {
        private static final RxRestService SERVICE = RetrofitHolder.CLIENT.create(RxRestService.class);
    }

    public static RxRestService getRxRestService() {
        return RxRestServiceHolder.SERVICE;
    }

    private static final class RestServiceHolder {
        private static final RestService SERVICE = RetrofitHolder.CLIENT.create(RestService.class);
    }

    public static RestService getRestService() {
        return RestServiceHolder.SERVICE;
    }

    /**
     * 得到cookie
     */
    public static CookieManger getCookie() {
        return RetrofitHolder.CLIENT.getCookie();
    }

    // 可在 App 运行时,随时切换 BaseUrl (指定了 Domain-Name header 的接口)
    public static void putDomain(String name, String baseUrl) {
        RetrofitHolder.CLIENT.putDomain(name, baseUrl);
    }
}
